<template>
  <div class="wrap">
    <!-- 刷新列表按钮 -->
    <Button type="primary" style="margin:8px 0 0" shape="circle" @click="refresh(true)">刷新列表</Button>

    <div style="position:relative">
        <!-- 加载 -->
        <Spin size="large" fix v-if="loading"></Spin>

        <!-- 列表 -->
        <roomLicens v-for="(item, index) in data" 
        :key="index" 
        :lockDetail="item.device" 
        :isFromRenter="true" 
        :passwords="item.passwords" 
        @refresh="refresh" 
        :roomName="item.room_name"></roomLicens>
    </div>
    
  </div>
</template>

<script>
import { http, api } from '@/libs/http'
import { DeviceTypeEnum } from '@/libs/const'
import roomLicens from '../../tenancy-device/roomLicens'
export default {
  data () {
    return {
      data: [], // 数组列表
      loading: false // 是否正在加载
    }
  },

  props: {
    leaseId: {
      // 租约id
      required: true,
      type: String
    }
  },

  components: { roomLicens },

  mounted () {
    this.getData()
  },

  methods: {
    /**
         * 通过租约id获取房间和
         */
    getData (pos = false) {
      this.loading = true
      pos && (this.data = [])
      http.request(this, api.leases_grant_record, [this.leaseId], null, (res, err) => {
        if (err) {
          return
        }
        this.loading = false
        this.constructData(res)
      })
    },

    /**
         * @param {Array} data 房间和公区返回
         */
    constructData (data) {
      let arr = []

      data.map(value => {
        const { devices, passwords, room_name } = value

        const index = this.getLock(devices) // 返回门锁的下标如果为-1表示没有找到

        if (index !== -1) {
          const { room_id } = devices[index]
          devices[index].roomId = room_id // 因为roomLicens组件用的是roomId作为prop的子参数，改roomLicens影响比较大，所以构造一个roomId字段
          arr.push({ device: devices[index], passwords, room_name })
        }
      })

      this.data = arr
    },

    /**
         * 找到门锁设备的下标，如果没有找到则返回-1
         * @param {Array} devices 设别列表
         */
    getLock (devices) {
      let index = -1

      for (let i = 0; i < devices.length; i++) {
        const { device_type } = devices[i]
        if (DeviceTypeEnum.LOCK === device_type) {
          index = i
          break
        }
      }
      return index
    },

    /**
         * 刷新列表
         */
    refresh () {
      this.getData(true)
    }
  }
}
</script>
<style lang='less' scoped>
.wrap {
    min-height: 500px;
}
</style>